package 快排;

import java.util.Random;

/**
 * @Date 2024/10/8 9:39
 * @description: 快排
 * .
 * @Author LittleNight
 */
public class likou912lianxi {
    // 练习快速排序
    public int[] sortArray(int[] nums) {
        qsort(0, nums.length - 1, nums);
        return nums;
    }

    public void qsort(int l, int r, int[] nums) {
        if(l >= r) return;

        // 数组分三块
        int key = nums[new Random().nextInt(r - l + 1) + l];
        int left = l - 1, right = r + 1, i = l;
        while(i < right) {
            if(nums[i] < key) swap(nums, ++left, i++);
            else if(nums[i]== key) i++;
            else swap(nums, --right, i);
        }
        // [l, left][left + 1, right - 1][right, r]
        qsort(l, left, nums);
        qsort(right, r, nums);
    }
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

}
